package com.jmall.base.core.security;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import com.jmall.admin.dao.RbacDAO;
import com.jmall.user.dao.UserDAO;

@Component("customRealm")
public class CustomRealm extends AuthorizingRealm {
	
	@Resource(name="userDAO")
	private UserDAO usersDAO = null;
	@Resource(name="rbacDAO")
	private RbacDAO rbacDAO = null;
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		Map user = (Map)pc.getPrimaryPrincipal();
		Integer empId = (Integer)user.get("emp_id");
		
		List<Map> list = rbacDAO.findRolesByEmp(empId);
		Set<String> roles = new TreeSet();
		for(Map role : list){
			roles.add((String)role.get("role_code"));
		}
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();		
		authorizationInfo.setRoles(roles);
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username = (String) token.getPrincipal();
		List<Map> userlist = usersDAO.findUserInfoByUsername(username);
		if(userlist.size() == 0){
			 throw new UnknownAccountException(username + "用户不存在");
		}
		Map user = (Map)userlist.get(0);
		if(((Integer)user.get("status") != 1)){
			throw new LockedAccountException(username + "用户当前状态不可用");
		}
		AuthenticationInfo authInfo =  new SimpleAccount(user ,user.get("password").toString() , this.getName());
		return authInfo;
	}

}
